package org.tom.org.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.tom.basic.util.JsonResult;
import org.tom.basic.util.PageList;
import org.tom.org.domain.Department;
import org.tom.org.query.DepartmentQuery;
import org.tom.org.service.IDepartmentService;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;


    @ApiOperation(value = "部门查询单个部门",notes = "通过id进行查询")
    @GetMapping("{id}")  // get方法的请求，参数为id查询单条数据
    public Department loadOne(@PathVariable("id") Long id){
        Department department = departmentService.findById(id);
        return department;
    }

    @ApiOperation(value = "查询所有的部门",notes = "不需要任何参数")
    @GetMapping // 查询所有
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    @ApiOperation(value = "部门删除",notes = "通过id进行删除")
    @DeleteMapping("{id}") // 删除携带参数id
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }

    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    @PutMapping // 修改和添加
    public JsonResult updateAndSave(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.insert(department);
            }else {
                departmentService.update(department);
            }
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }

    @ApiOperation(value = "分页显示",notes = "传输分页需要的当前页和每页显示的条数")
    @PostMapping // 分页接受分页数据用对象
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryList(departmentQuery);
    }

    @ApiOperation(value = "批量删除部门",notes = "传id集合")
    @PatchMapping
    public JsonResult patchDelete(@RequestBody List<Long> ids){ // 使用数组类型的集合接受参数
        try {
            departmentService.patchDelete(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }

    @ApiOperation(value = "查询所有的部门子部门",notes = "不需要任何参数")
    @GetMapping("/tree") // 查询所有
    public List<Department> findAllChildren(){
        return departmentService.loadTree();
    }

}
